/**
 * 招聘需求套件
 */
import React, { useEffect, useState } from 'react';
import { Form, Card, Input, DatePicker, InputNumber, Select, Radio, message, Spin, Button, Tooltip } from 'antd';
import { withRouter } from 'umi';
import { connect } from 'umi';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';

import moment from 'moment';
import { IM } from '@/molecules';
import { isArray } from 'lodash';
import { useRequest, defaultFormatResult } from '@/hooks';
import { BaseWrapper } from '@/pages/Organization/OrgFlow/components';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import { getJobList } from '@/services/organization';
import { dictionaryList } from '@/services/dictionary';
import { getPositionTags } from '@/pages/Recruitment/service';
import { getOrgTree, createGroup, bindGroupId } from './service';
import styles from './index.less';

const { TextArea } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';

const Recruit = ({
    form,
    location,
    wrapperLayout,
    dataSource,
    formValueMap,
    approve,
    status,
    currentcandidateflag, // 这个字段上层注入的，只能全小写，无奈
    processInstanceId,
    user
}) => {
    const { query } = location;
    const { children: list } = dataSource;
    const { getFieldDecorator, setFieldsValue } = form;
    const hiDataId = location?.query?.hiDataId || formValueMap?.hiDataId;
    const [jobList, setJobList] = React.useState([]);
    const [tips, setTips] = React.useState([]);
    const [detailLoading, setDetailLoading] = useState(false);
    const [postLoading, setPostLoading] = useState(false);
    const [orgNameLoading, setOrgNameLoading] = useState(false);
    const [companyNameLoading, setCompanyNameLoading] = useState(false);
    const [dictObjLoading, setDictObjLoading] = useState(false);

    // 旧数据差异化对比name
    const [recruitDegreeNameOld, setRecruitDegreeNameOld] = useState(null);
    const [workYearsNameOld, setWorkYearsNameOld] = useState(null);
    const [recruitSexNameOld, setRecruitSexNameOld] = useState(null);
    const [workNatureNameOld, setWorkNatureNameOld] = useState(null);
    const [positionNameOld, setPositionNameOld] = useState(null);

    const [organizationNameOld, setOrganizationNameOld] = useState(undefined);
    const [organizationName, setOrganizationName] = useState(undefined);
    const [organizationCode, setOrganizationCode] = useState(undefined);
    const [companyNameOld, setCompanyNameOld] = useState(undefined);
    const [companyName, setCompanyName] = useState(undefined);
    const [timeTipsValue, setTimeTipsValue] = useState(undefined);
    const [tagList, setTagList] = React.useState([]);
    const [dataArr, setDataArr] = useState(null); // 基础信息

    const [commProps, setCommProps] = useState({
        form,
        disabled: true
    });

    const [dictObj, setDictObj] = React.useState(null);

    // 创建讨论群
    const { data: groupInfo, loading: groupLoading, run: createNewGroup } = useRequest(createGroup, {
        manual: true,
        ...defaultFormatResult,
        onSuccess: res => {
            if (res) {
                form.setFieldsValue({
                    groupId: res
                });
                if (processInstanceId || query?.processInstanceId) {
                    bindGroupId({
                        processInstanceId: processInstanceId || query?.processInstanceId,
                        groupId: res
                    });
                }
            }
        }
    });

    const handleCreateGroup = () => {
        if (!(approve && isArray(approve) && approve.length > 0)) {
            message.error('未获取到相关人员，无法创建讨论群');
            return;
        }
        const arr = approve.reduce((prev, cur) => {
            const { userList = [], proxyList = [] } = cur;
            return [...new Set([...prev, ...userList, ...proxyList])];
        }, []);

        const memberList = arr
            ?.filter(item => !!item)
            .map(item => ({
                memberId: item,
                type: item === user.employeeCode ? 1 : 0
            }));

        const params = {
            groupName: `招聘需求申请讨论群-${dataArr?.dutyName}`,
            owner: user.employeeCode,
            list: memberList,
            operator: user.employeeCode,
            type: 0,
            extra: JSON.stringify({ closeNotify: 1 })
        };
        createNewGroup(params);
    };

    // 用code转换成name
    const filterJobCode = (data, values) => {
        let selectValue = '';
        if (data) {
            data.forEach(item => {
                if (values.indexOf(item.positionCode) > -1) {
                    selectValue = `${item.positionName} / ${item.rankValue}`;
                }
            });
            return selectValue;
        }
        return null;
    };

    // 获取城市列表
    const fetchJobList = async (name = '') => {
        setPostLoading(true);
        const res = await getJobList({ postName: name.trim(), pageSize: 99999 });
        const { code, data, msg } = res;
        if (code === 10000) {
            setJobList(data?.rows || []);
            // 过滤差异化对比的岗位值
            if (tips?.positionCode) {
                const positionValue = filterJobCode(data?.rows, tips?.positionCode);
                setPositionNameOld(positionValue);
            }
            setPostLoading(false);
        } else {
            setPostLoading(false);
            message.error(msg);
        }
    };
    // 用code转换成name
    const filterCode = (data, values) => {
        let selectValue = '';
        if (data) {
            data.forEach(item => {
                if (values.indexOf(item.dictValue) > -1) {
                    selectValue = item.dictName;
                }
            });
            return selectValue;
        }
        return null;
    };
    // 获取机构列表
    const fetchOrganization = async () => {
        // 新数据
        if (dataArr?.organizationCode) {
            setOrgNameLoading(true);
            const { msg, code, data } = await getOrgTree({ organizationCode: dataArr?.organizationCode });
            if (code === 10000) {
                setOrgNameLoading(false);
                setOrganizationName(data?.organizationName);
                setOrganizationCode(data?.organizationCode);
            } else {
                setOrgNameLoading(false);
                message.error(msg);
            }
        }
        // 旧数据
        if (tips?.organizationCode) {
            const { msg, code, data } = await getOrgTree({ organizationCode: tips?.organizationCode });
            if (code === 10000) {
                setOrganizationNameOld(data?.organizationName);
            } else {
                message.error(msg);
            }
        }
    };

    // 获取行政机构列表
    const fetchCompany = async () => {
        // 新数据
        if (dataArr?.companyCode) {
            setCompanyNameLoading(true);
            const { msg, code, data } = await getOrgTree({ organizationCode: dataArr?.companyCode });
            if (code === 10000) {
                setCompanyNameLoading(false);
                setCompanyName(data?.organizationName);
            } else {
                setCompanyNameLoading(false);
                message.error(msg);
            }
        }
        // 旧数据
        if (tips?.companyCode) {
            const { msg, code, data } = await getOrgTree({ organizationCode: tips?.companyCode });
            if (code === 10000) {
                setCompanyNameOld(data?.organizationName);
            } else {
                message.error(msg);
            }
        }
    };

    // 读取字典
    const fetchDictionary = async () => {
        setDictObjLoading(true);
        const res = await dictionaryList({
            codes: ['jobNature', 'candidateSexType', 'agreeType', 'timeEmployedType']
        });
        const { code, data, msg } = res;
        if (code === 10000) {
            setDictObjLoading(false);
            const obj = {};
            data.forEach(item => {
                if (obj[item.code]) {
                    obj[item.code].push(item);
                } else {
                    obj[item.code] = [item];
                }
            });
            setDictObj(obj);

            // 差异化对比旧数据
            if (tips?.recruitDegree) {
                const recruitDegreeValueOld = filterCode(obj?.agreeType, tips?.recruitDegree);
                setRecruitDegreeNameOld(recruitDegreeValueOld);
            }
            if (tips?.workYears) {
                const workYearsValueOld = filterCode(obj?.timeEmployedType, tips?.workYears);
                setWorkYearsNameOld(workYearsValueOld);
            }
            if (tips?.recruitSex) {
                const recruitSexValueOld = filterCode(obj?.candidateSexType, tips?.recruitSex);
                setRecruitSexNameOld(recruitSexValueOld);
            }
            if (tips?.workNature) {
                const workNatureNameCNOld = filterCode(obj?.jobNature, tips?.workNature);
                setWorkNatureNameOld(workNatureNameCNOld);
            }
            // 差异化对比旧数据
        } else {
            setDictObjLoading(false);
            message.error(msg);
        }
    };

    // 渲染选择工作年限
    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Option>
            ));
        }
        return null;
    };
    // 渲染字典
    const renderRadios = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Radio value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Radio>
            ));
        }
        return null;
    };

    // 获取标签
    const fetchPositionTags = async tagName => {
        const res = await getPositionTags(tagName);
        const { code, data, msg } = res;
        if (code === 10000) {
            setTagList([...new Set(data || [])]);
        } else {
            message.error(msg);
        }
    };
    // 获取详情
    const fetchApproveData = async () => {
        const { msg, code, data } = await getPostApplyData(hiDataId);
        setDetailLoading(true);
        if (code === 10000 && data) {
            setCommProps({ ...commProps });
            const { compareDataField, oldBusinessData } = data;

            // 基础信息 差异数据
            const tipsData = {};
            if (compareDataField?.updateFieldNames) {
                compareDataField.updateFieldNames.forEach(v => {
                    tipsData[v] = oldBusinessData[v];
                });
            }
            setDataArr({ ...data });
            setTips(tipsData);
            setDetailLoading(false);

            // 处理时间差异化对比
            let timeTips;
            if (tipsData?.entryDateStart && tipsData?.entryDateEnd) {
                timeTips = `${tipsData?.entryDateStart} ~ ${tipsData?.entryDateEnd}`;
            }
            if (tipsData?.entryDateStart && !tipsData?.entryDateEnd) {
                timeTips = `${tipsData.entryDateStart} ~ ${data.entryDateEnd}`;
            }
            if (!tipsData?.entryDateStart && tipsData?.entryDateEnd) {
                timeTips = `${data.entryDateStart} ~ ${tipsData.entryDateEnd}`;
            }
            setTimeTipsValue(timeTips);
        } else {
            message.error(msg);

            setDetailLoading(false);
        }
    };

    // 拉取审批数据
    useEffect(() => {
        if (hiDataId) {
            fetchApproveData();
        }
    }, [hiDataId]);
    React.useEffect(() => {
        if (dataArr) {
            fetchDictionary();
            fetchJobList();
            fetchPositionTags();
            fetchOrganization();
            fetchCompany();
            setFieldsValue({ recruitment_OrganizationCode: dataArr?.organizationCode }); // 触发预览！
        }
    }, [dataArr, tips]);

    const renderIm = () => {
        if (formValueMap?.groupId || groupInfo) {
            return <IM groupId={formValueMap?.groupId || groupInfo} readOnly={status === 1} />;
        }
        if ((status !== 1 && currentcandidateflag === 1) || !hiDataId || !query?.processInstanceId) {
            return (
                <Tooltip title="系统将自动为招聘发起人、审批人创建IM讨论群">
                    <Button
                        type="primary"
                        ghost
                        disabled={!hiDataId || !approve || approve.length === 0}
                        loading={groupLoading}
                        onClick={handleCreateGroup}
                    >
                        创建讨论群
                    </Button>
                </Tooltip>
            );
        }
        return '无';
    };

    return (
        <Card bordered={false}>
            <div style={{ position: 'relative' }}>
                <div className={styles.formIntro}>
                    <span>招聘需求申请流程</span>
                    <div className={styles.info}>以下是招聘需求详情，请审阅</div>
                </div>
                <Spin spinning={detailLoading}>
                    <Form layout="horizontal" className={styles.postEdit} {...wrapperLayout}>
                        {list.map(item => {
                            const { label, formId, rules, extra } = item;
                            let { initialValue } = item;
                            if (formId === 'organizationName') {
                                initialValue = organizationName;
                            }
                            if (formId === 'recruitment_OrganizationCode') {
                                initialValue = organizationCode;
                            }
                            if (formId === 'recruitNums') {
                                initialValue = dataArr?.recruitNums;
                            }
                            if (formId === 'dutyName') {
                                initialValue = dataArr?.dutyName;
                            }
                            return (
                                <Form.Item
                                    label={label}
                                    key={formId}
                                    extra={extra}
                                    style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                                >
                                    {getFieldDecorator(formId, {
                                        initialValue,
                                        rules
                                    })(<AutoRenderComponent form={form} config={item} />)}
                                </Form.Item>
                            );
                        })}
                        <Form.Item style={{ display: 'none' }}>
                            {form.getFieldDecorator('hiDataId', {
                                initialValue: hiDataId
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item label="IM沟通">{renderIm()}</Form.Item>
                        <Form.Item style={{ display: 'none' }}>
                            {form.getFieldDecorator('groupId', {
                                initialValue: formValueMap?.groupId || ''
                            })(<Input />)}
                        </Form.Item>

                        <BaseWrapper title="基本信息">
                            <Form.Item label="需求部门" required>
                                <Spin spinning={orgNameLoading}>
                                    <Difference tip={organizationNameOld || undefined}>
                                        <Input value={organizationName || undefined} disabled />
                                    </Difference>
                                </Spin>
                            </Form.Item>
                            <Form.Item label="岗位名称" required>
                                <Spin spinning={postLoading}>
                                    <Difference tip={tips?.dutyName}>
                                        <Input value={dataArr?.dutyName} disabled />
                                    </Difference>
                                </Spin>
                            </Form.Item>
                            <Form.Item label="需求人数" required>
                                <Difference tip={tips?.recruitNums}>
                                    <InputNumber
                                        min={0}
                                        max={999}
                                        precision={0}
                                        placeholder="请输入需求人数"
                                        style={{ width: '100%' }}
                                        disabled
                                        value={dataArr?.recruitNums}
                                    />
                                </Difference>
                            </Form.Item>
                            <Form.Item label="行政机构" required>
                                <Spin spinning={companyNameLoading}>
                                    <Difference tip={companyNameOld || undefined}>
                                        <Input value={companyName || undefined} disabled />
                                    </Difference>
                                </Spin>
                            </Form.Item>
                            <Form.Item label="工作城市" required>
                                <Difference tip={tips?.workCity}>
                                    <Input value={dataArr?.workCity} disabled />
                                </Difference>
                            </Form.Item>
                            <Form.Item label="工作性质">
                                <Spin spinning={dictObjLoading}>
                                    <Difference tip={workNatureNameOld || undefined}>
                                        <Radio.Group value={dataArr?.workNature} disabled>
                                            {renderRadios(dictObj?.jobNature)}
                                        </Radio.Group>
                                    </Difference>
                                </Spin>
                            </Form.Item>
                            <Form.Item label="到岗时间">
                                <Difference tip={timeTipsValue}>
                                    {dataArr?.entryDateStart ? (
                                        <RangePicker
                                            style={{ width: '100%' }}
                                            disabled
                                            value={[
                                                moment(dataArr?.entryDateStart, dateFormat),
                                                moment(dataArr?.entryDateEnd, dateFormat)
                                            ]}
                                            format={dateFormat}
                                        />
                                    ) : (
                                        <RangePicker style={{ width: '100%' }} disabled format={dateFormat} />
                                    )}
                                </Difference>
                            </Form.Item>
                        </BaseWrapper>
                        <BaseWrapper title="职位要求">
                            <Form.Item label="经验和学历" style={{ marginBottom: 0 }} required>
                                <div style={{ display: 'flex', alignItems: 'center' }}>
                                    <Form.Item label="" colon={false} style={{ width: '50%', marginRight: 8 }}>
                                        <Spin spinning={dictObjLoading}>
                                            <Difference tip={workYearsNameOld || undefined}>
                                                <Select
                                                    placeholder="请选择工作年限"
                                                    allowClear
                                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                                    disabled
                                                    value={dataArr?.workYears}
                                                >
                                                    {renderOptions(dictObj?.timeEmployedType)}
                                                </Select>
                                            </Difference>
                                        </Spin>
                                    </Form.Item>
                                    <Form.Item label="" colon={false} style={{ width: '50%' }}>
                                        <Spin spinning={dictObjLoading}>
                                            <Difference tip={recruitDegreeNameOld || undefined}>
                                                <Select
                                                    placeholder="请选择学历"
                                                    allowClear
                                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                                    disabled
                                                    value={dataArr?.recruitDegree}
                                                >
                                                    {renderOptions(dictObj?.agreeType)}
                                                </Select>
                                            </Difference>
                                        </Spin>
                                    </Form.Item>
                                </div>
                            </Form.Item>
                            <Form.Item label="性别">
                                <Difference tip={recruitSexNameOld || undefined}>
                                    <Radio.Group disabled value={dataArr?.recruitSex}>
                                        {renderRadios(dictObj?.candidateSexType)}
                                    </Radio.Group>
                                </Difference>
                            </Form.Item>
                            <Form.Item label="匹配职位" required>
                                <Difference tip={positionNameOld || undefined}>
                                    <Select
                                        placeholder="请选择匹配职位"
                                        allowClear
                                        showSearch
                                        optionFilterProp="label"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        disabled
                                        value={dataArr?.positionCode}
                                    >
                                        {jobList?.map(item => (
                                            <Option
                                                value={item.positionCode}
                                                key={item.positionCode}
                                                label={item.positionName}
                                            >
                                                {item.positionName}
                                                {item.rankValue ? '/' : ''}
                                                {item.rankValue}
                                            </Option>
                                        ))}
                                    </Select>
                                </Difference>
                            </Form.Item>
                            <Form.Item label="职位要求" required>
                                <Difference tip={tips?.positionDesc}>
                                    <div>
                                        <TextArea
                                            disabled
                                            placeholder="请输入职位要求"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={800}
                                            value={dataArr?.positionDesc}
                                        />
                                    </div>
                                </Difference>
                            </Form.Item>
                            <Form.Item label="岗位要求">
                                <Difference tip={tips?.jobRequirement}>
                                    <div>
                                        <TextArea
                                            disabled
                                            placeholder="请输入岗位要求"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={2000}
                                            value={dataArr?.jobRequirement}
                                        />
                                    </div>
                                </Difference>
                            </Form.Item>

                            <Form.Item label="职位关键词">
                                <Difference tip={tips?.positionTag}>
                                    <Select
                                        mode="multiple"
                                        style={{ width: '100%' }}
                                        placeholder="请选择职位关键词"
                                        allowClear
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        disabled
                                        value={dataArr?.positionTag || undefined}
                                    >
                                        {tagList.map(item => (
                                            <Option value={item} key={item}>
                                                {item}
                                            </Option>
                                        ))}
                                    </Select>
                                </Difference>
                            </Form.Item>
                        </BaseWrapper>
                    </Form>
                </Spin>
            </div>
        </Card>
    );
};

export default withRouter(connect(({ user }) => ({ user: user.currentUser }))(Recruit));
